let _Vue = null
export default class Myrouter {
    constructor(options) {
        this.options = options
        this.routeMap = {}
        this.data = _Vue.observable({
            current: location.pathname
        })
    }
    static install(Vue) {
        // 判断当前插件是否安装
        if (Myrouter.install.installed) {
            return
        }
        Myrouter.install.installed = true
        // 把Vue构造函数记录到全局变量
        _Vue = Vue
        // 把router对象注入到 Vue实例 上
        _Vue.mixin({
            beforeCreate(){
                if (this.$options.router) { // 只有Vue实例上会传递router参数，在组件中没有该属性
                    _Vue.prototype.$router = this.$options.router
                    this.$options.router.init()
                }
            },
        })
    }

    createRouteMap() {
        this.options.routes.forEach(route => {
            this.routeMap[route.path] = route.component
        })
    }

    initComponents(Vue) {
        Vue.component('router-link', {
            props: {
                to: String
            },
            render(h) {
                return h('a', {
                    attrs: {
                        href: this.to
                    },
                    on: {
                        click: this.clickHandler
                    }
                }, [
                    this.$slots.default
                ])
            },
            methods:{
                clickHandler(e) {
                    e.preventDefault()
                    history.pushState({}, '', this.to)
                    this.$router.data.current = this.to
                }
            },
        })
        const self = this
        Vue.component('router-view', {
            render(h) {
                return h(self.routeMap[self.data.current])
            }
        })
    }
    initEvent() {
        window.onpopstate = () => {
            this.data.current = window.location.pathname
        }
    }
    init() {
        this.createRouteMap()
        this.initComponents(_Vue)
        this.initEvent()
    }
}